package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.User;
import com.conversationboard.model.preferences.UserPreferences;

@WebServlet(name = "PreferencesControllerServlet", urlPatterns = "/PreferencesControllerServlet")
public class PreferencesControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 3101385828070615643L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String timeZone = request.getParameter("timezone");

		String showImages = request.getParameter("showimages");
		String relativeTimes = request.getParameter("relativetimes");
		String hideThreadInfo = request.getParameter("hidethreadinfo");
		String hidePolls = request.getParameter("hidepolls");
		String hideTimeDisplay = request.getParameter("hidetimedisplay");
		String useTraditionalBookmarks = request.getParameter("usetraditionalbookmarks");
		String displayLastUpdatedBy = request.getParameter("displaylastupdatedby");

		try {

			String loginId = request.getUserPrincipal().getName();
			User user = User.get(loginId);

			UserPreferences preferences = user.getPreferences();

			preferences.setShowImages(convertStringToBoolean(showImages));
			preferences.setDisplayRelativeTimes(convertStringToBoolean(relativeTimes));
			preferences.setTimeZoneString(timeZone);
			preferences.setHideThreadInfo(convertStringToBoolean(hideThreadInfo));
			preferences.setHidePolls(convertStringToBoolean(hidePolls));
			preferences.setHideTimeDisplay(convertStringToBoolean(hideTimeDisplay));
			preferences.setUseTraditionalBookmarks(convertStringToBoolean(useTraditionalBookmarks));
			preferences.setHideLastUpdatedBy(convertStringToBoolean(displayLastUpdatedBy));

			preferences.store();

			response.sendRedirect(request.getContextPath() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}


	private static boolean convertStringToBoolean(String input) {

		if (input == null) {
			return false;
		} else {
			return true;
		}

	}

}
